<template>
  <div class="login">
    <el-card class="box-card">
      <div class="title">选课管理系统</div>
      <el-form :model="form" :rules="rules" ref="loginForm" label-width="0">
        <el-form-item prop="username">
          <el-input prefix-icon="el-icon-user" v-model="form.username" placeholder="账号" style="width: 350px;" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input prefix-icon="el-icon-lock" v-model="form.password" type="password" placeholder="密码" style="width: 350px;" />
        </el-form-item>
        <el-form-item prop="userType">
          <el-radio-group v-model="form.userType">
            <el-radio :label="1">学生</el-radio>
            <el-radio :label="2">教师</el-radio>
            <el-radio :label="3">管理员</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width: 350px;" @click="submit">登录</el-button>
        </el-form-item>
        <el-form-item v-if="isDevelopment">
          <el-button type="success" style="width: 350px;" @click="quickLogin">快速登录 (管理员)</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// 统一从 index.js 导入，使用正式导出的 loginStatus 名称
import { login, loginStatus } from '@/api'
export default {
  data() {
    return {
      form: {
        username: '',
        password: '',
        userType: 3
      },
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        userType: [
          { required: true, message: '请选择身份', trigger: 'change' }
        ]
      },
      userTypes: [
        { label: '学生', value: 1 },
        { label: '教师', value: 2 },
        { label: '管理员', value: 3 }
      ]
    }
  },
  computed: {
    isDevelopment() {
      return process.env.NODE_ENV === 'development'
    }
  },
  mounted() {
    // 开发模式下自动填入默认管理员账号
    if (process.env.NODE_ENV === 'development') {
      this.form.username = 'admin';
      this.form.password = '123456';
      this.form.userType = 3;
    }
  },
  methods: {
    submit() {
      this.$refs.loginForm.validate(async valid => {
        if (valid) {
          try {
            // 登录
            await login(this.form)
            
            // 获取用户信息
            let userInfo = null
            try {
              const statusRes = await loginStatus()
              userInfo = statusRes.data
            } catch (error) {
              console.warn('获取用户信息失败:', error)
            }
            
            this.$message.success('登录成功')
            // 确保写入 userType（后端若未返回则用登录表单选择的身份）
            if (userInfo && !userInfo.userType) {
              userInfo.userType = this.form.userType
            }
            // 补充id（仅学生，后端未返回时用用户名兜底，建议后端返回真实id）
            if (userInfo && !userInfo.id && this.form.userType === 1) {
              userInfo.id = this.form.username
            }
            if (!userInfo) {
              // loginStatus 失败时最少存入 userType 供前端权限判断
              userInfo = { userType: this.form.userType, username: this.form.username, id: this.form.username }
            }
            try { localStorage.setItem('userType', String(userInfo.userType)) } catch(e) {}
            this.$store.commit('user/updateloggedIn', userInfo)
            
            if (this.$route.path !== '/home') {
              this.$router.push('/home').catch(() => {})
            }
          } catch (error) {
            console.error('登录失败:', error)
            this.$message.error('登录失败，请检查用户名和密码')
          }
        }
      })
    },
    quickLogin() {
      // 快速登录管理员账户
      this.form.username = 'admin';
      this.form.password = '123456';
      this.form.userType = 3;
      this.submit();
    }
  }
}
</script>

<style scoped>
html, body, #app {
  height: 100vh;
  margin: 0;
  padding: 0;
}

.login {
  min-height: 100vh;
  height: 100vh;
  background-image: url(../../public/img/GzbSBLma4AENkdI\ \(1\).jpg);
  background-size: 100% ;
  display: flex;
  justify-content: center;
  align-items: center;
}


.box-card {
  width: 420px;
  min-height: 320px;
  background: rgba(0,0,0,0.6) !important;
  border-radius: 12px;
  box-shadow: 0 4px 24px rgba(0,0,0,0.2);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.box-card .el-card__body {
  background: transparent !important;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.title {
  color: #fff;
  font-size: 32px;
  text-align: center;
  margin-bottom: 28px;
  font-weight: bold;
  letter-spacing: 2px;
}
.el-form {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.el-radio-group {
  margin-bottom: 10px;
}
</style>